package com.sharp.core.voxel.resource;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import com.jme3.math.ColorRGBA;
import com.sharp.core.utils.Util;
import com.sharp.core.voxel.Voxel;
import com.sharp.core.voxel.VoxelArray;

public class Vox extends VoxelResource {

	private String name;
	private int width, height, depth;
	private byte[] voxels;
	private byte[] palette;
	
	public Vox(String path) throws IOException {
		load(path);
	}
	
	private String getOnlyFileName(String name) {
		int index = name.lastIndexOf(File.separator);
		if ( index == -1 )
			return name;
		return name.substring( index+1 );
	}
	
	@Override
	public final void load(String path) throws IOException {
		
		this.name = getOnlyFileName(path);
		File file = new File(path);
		
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		byte[] tmp = new byte[(int) file.length()];
		in.readFully(tmp);
		
		ByteBuffer buffer = ByteBuffer.wrap(tmp);
		buffer.order(ByteOrder.LITTLE_ENDIAN);
		
		width = buffer.getInt();
		height = buffer.getInt();
		depth = buffer.getInt();
		
		
		voxels = new byte[width*height*depth];
		buffer.get(voxels);
		
		palette = new byte[256*3];
		buffer.get(palette);
		
		in.close();
	}

	@Override
	public final VoxelArray convertToVoxelArray() {
		VoxelArray ret = new VoxelArray(width, height, depth);
		
		int i = 0;
		for ( int z = 0; z < depth; ++z ) {
			for ( int y = 0; y < height; ++y ) {
				for ( int x = 0; x < width; ++x, ++i ) {
					if ( Util.unsignedByteToInt(voxels[i]) == 255 )
						continue;
					ColorRGBA c = getPalette(voxels[i]);
					Voxel v = new Voxel(c);
					ret.setVoxel(x, y, z, v);
				}
			}
		}
		return ret;
	}

	private ColorRGBA getPalette(byte i) {
		int index = Util.unsignedByteToInt(i) * 3;
		float r = palette[index] / 63.0f;
		float b = palette[index+1] / 63.0f;
		float g = palette[index+2] / 63.0f;
		return new ColorRGBA(r, g, b, 1.0f);
	}

	@Override
	public String toString() {
		return name+" (" + width+"x" + height+"x" + depth + ")";
	}
	
	
}
